package com.zhuiwei.bigdata.zookeeper.server;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * zookeeper注册服务器
 * @author zhuiwei
 */
public class ZkServer {

    //连接地址
    private static String connectString="192.168.154.101:2181";
    //超时时间设置
    private static int sessionTimeOut=2000;
    private ZooKeeper zk = null;

    /**
     * 获取连接
     * @throws IOException 异常
     */
    public void getConnect() throws Exception {
        zk=new ZooKeeper(connectString, sessionTimeOut, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                //监听回调
            }
        });
    }

    /**
     * 注册服务器
     * @param path 节点路径
     * @param data 数据
     * @return 节点路径
     * @throws Exception 异常
     */
    public String  registServer(String path,String data) throws Exception {
        String createPath= zk.create(path,data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
        return createPath;
    }

    public static void main(String[] args) throws Exception {
       ZkServer zk =new ZkServer();
       zk.getConnect();
       zk.registServer("/server/node1","子节点");
       Thread.sleep(Long.MAX_VALUE);
    }
}
